<template>
  <a-card>
    <!-- 查询区域 -->
    <div>
      <a-form layout="horizontal" :labelCol="{ span: 8 }" :wrapperCol="{ span: 15 }">
        <div class="fold">
          <a-row>
            <a-col :md="6" :sm="24">
              <a-form-item label="角色ID">
                <a-input
                  v-model="searchForm.roleId"
                  placeholder="角色ID"
                  @keyup.enter="handleSearch"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="角色名称">
                <a-input
                  v-model="searchForm.roleName"
                  placeholder="角色名称"
                  @keyup.enter="handleSearch"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="创建时间">
                <a-input
                  v-model="searchForm.createTime"
                  placeholder="创建时间"
                  @keyup.enter="handleSearch"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item>
                <a-button v-permission="`basic:role:list`" type="primary" @click="handleSearch"
                  >查询</a-button
                >
                <a-button class="ml-8">重置</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </div>
      </a-form>
    </div>

    <!-- 表格区域 -->
    <div>
      <div class="operator">
        <a-button v-permission="`basic:role:add`" class="mr-8" type="primary" @click="handleAddRole"
          >新增</a-button
        >
        <a-button
          v-permission="`basic:role:batchDel`"
          class="mr-8"
          type="danger"
          @click="handleDelAll"
          >批量删除</a-button
        >
      </div>
      <a-table
        bordered
        :loading="loading"
        :columns="columns"
        :row-key="item => item.id"
        :data-source="dataSource"
        :pagination="pagination"
        :row-selection="rowSelection"
      >
        <span slot="action" slot-scope="item">
          <a v-permission="`basic:role:update`" @click="handleEditRole(item)">修改</a>
          <a-divider type="vertical" />
          <a v-permission="`basic:role:del`" style="color:#ff4d4f;" @click="handleDelRole(item)"
            >删除</a
          >
        </span>
      </a-table>
    </div>

    <!-- 新增/修改弹窗 -->
    <a-modal
      :title="modalTitle"
      :visible="visible"
      :maskClosable="false"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form
        :form="addForm"
        :labelCol="formItemLayout.labelCol"
        :wrapperCol="formItemLayout.wrapperCol"
      >
        <a-form-item label="角色名称">
          <a-input
            v-decorator="['roleName', { rules: [{ required: true, message: '请输入角色名称' }] }]"
            placeholder="请输入"
          />
        </a-form-item>
        <a-form-item label="备注">
          <a-input v-decorator="['remark']" placeholder="请输入" />
        </a-form-item>
        <a-form-item label="授权">
          <a-tree
            :checkedKeys="menuIdList"
            checkable
            checkStrictly
            :tree-data="treeData"
            :replaceFields="replaceFields"
            @check="checkedKeys => (this.menuIdList = checkedKeys.checked)"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </a-card>
</template>

<script>
import moment from 'moment';
import { userService, basicService, systemService } from '@/services';

const columns = [
  {
    title: '角色ID',
    dataIndex: 'id',
    key: 'id',
    align: 'center',
    width: 100,
  },
  {
    title: '角色名称',
    dataIndex: 'roleName',
    key: 'roleName',
    align: 'center',
  },
  {
    title: '备注',
    key: 'remark',
    dataIndex: 'remark',
    align: 'center',
  },
  {
    title: '创建时间',
    key: 'createTime',
    dataIndex: 'createTime',
    customRender: text => {
      return moment(text).format('YYYY-MM-DD HH:mm:ss');
    },
    align: 'center',
    width: 200,
  },
  {
    title: '操作',
    key: 'action',
    scopedSlots: { customRender: 'action' },
    align: 'center',
    width: 150,
  },
];

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 },
};

export default {
  name: 'basicRole',

  data() {
    return {
      formItemLayout,
      columns,
      // 搜索表单
      searchForm: {
        id: null,
        roleName: '',
        createTime: '',
      },
      pagination: {
        showSizeChanger: true,
        pageSizeOptions: ['10', '50', '100', '200'],
        showQuickJumper: true,
        showTotal: total => `共${total}条`,
        current: 1,
        pageSize: 10,
        total: 0,
      },
      rowSelection: {
        selectedRowKeys: [],
        onChange: selectedRowKeys => (this.rowSelection.selectedRowKeys = selectedRowKeys),
      },
      loading: false,
      dataSource: [],
      type: 1, // 1-新增 2-修改
      visible: false,
      selectedItem: null,
      addForm: this.$form.createForm(this, { name: 'role-add-form' }),
      confirmLoading: false,
      treeData: [], // 权限树
      replaceFields: {
        key: 'id',
        value: 'id',
        title: 'name',
        children: 'children',
      },
      menuIdList: [],
    };
  },

  computed: {
    modalTitle() {
      return this.type === 1 ? '新增' : '修改';
    },
  },

  created() {
    const p1 = this.getDataSource();
    const p2 = this.getMenuTree();
    this.loading = true;
    Promise.all([p1, p2]).then(() => {
      this.loading = false;
    });
  },

  methods: {
    // 查询列表
    handleSearch() {
      this.getDataSource();
    },

    // 新增
    handleAddRole() {
      this.menuIdList.length = 0;
      this.type = 1;
      this.visible = true;
    },

    // 批量删除
    handleDelAll() {
      console.log('批量删除', this.rowSelection.selectedRowKeys);
    },

    // 删除
    handleDelRole(item) {
      console.log(item);
      const that = this;
      this.$confirm({
        title: '确认删除该角色吗？',
        content: () => <div style='color:red;'>删除后不可恢复！</div>,
        okText: '删除',
        okType: 'danger',
        cancelText: '取消',
        onOk() {
          const { id } = item;
          console.log(id);
          return new Promise(resolve => {
            basicService
              .delRole({ id })
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  that.$message.success('操作成功');
                  that.getDataSource();
                }
              })
              .finally(() => resolve());
          });
        },
        onCancel() {
          console.log('Cancel');
        },
      });
    },

    // 修改
    handleEditRole(item) {
      const { id, roleName, remark } = item;
      basicService.getRole({ id }).then(res => {
        if (res.code === '200') {
          this.menuIdList = res.data.menuList.map(item => item.id);
          this.$nextTick(() => {
            this.addForm.setFieldsValue({
              roleName,
              remark,
            });
          });
        }
      });

      this.selectedItem = item;
      this.type = 2;
      this.visible = true;
    },

    // 取消新建
    handleCancel() {
      this.visible = false;
      this.selectedItem = null;
      this.menuIdList = [];
      this.addForm.resetFields();
    },

    // 新建/修改确认
    handleOk() {
      this.addForm.validateFields((err, values) => {
        if (!err) {
          this.confirmLoading = true;
          console.log('Received values of form:', { ...values, menuIdList: this.menuIdList });
          if (this.type === 1) {
            basicService
              .addRole({ ...values, menuIdList: this.menuIdList })
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  this.$message.success('操作成功');
                  this.visible = false;
                  this.addForm.resetFields();
                  this.getDataSource();
                  this.menuIdList = [];
                }
              })
              .catch(e => {
                this.$message.error(e);
              })
              .finally(() => {
                this.confirmLoading = false;
              });
          } else {
            basicService
              .updateRole({ ...values, menuIdList: this.menuIdList, id: this.selectedItem.id })
              .then(res => {
                console.log(res);
                if (res.code === '200') {
                  this.$message.success('操作成功');
                  this.visible = false;
                  this.selectedItem = null;
                  this.addForm.resetFields();
                  this.getDataSource();
                  this.updatePerms();
                  this.menuIdList = [];
                }
              })
              .catch(e => {
                this.$message.error(e);
              })
              .finally(() => {
                this.confirmLoading = false;
              });
          }
        }
      });
    },

    // 获取数据
    getDataSource() {
      const params = {
        roleName: this.searchForm.roleName,
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
      };
      return new Promise(resolve => {
        basicService.getRoleList(params).then(res => {
          if (res.code === '200') {
            this.dataSource = res.data.content;
            this.pagination.total = res.data.totalElements;
            resolve();
          }
        });
      });
    },

    // 获取菜单树
    getMenuTree() {
      return new Promise(resolve => {
        systemService.getMenuTree().then(res => {
          if (res.code === '200') {
            // this.treeData = this.formatTreeData(res.data.rootNode);
            this.treeData = res.data.rootNode.children;
            resolve();
          }
        });
      });
    },

    // 处理菜单树
    formatTreeData(rootNode) {
      console.log(rootNode);
      return rootNode.children && rootNode.children.length
        ? rootNode.children.map(item => {
            return {
              title: item.name,
              value: item.id,
              key: item.id,
              children:
                item.children && item.children.length
                  ? item.children.map(subItem => {
                      return {
                        title: subItem.name,
                        value: subItem.id,
                        key: subItem.id,
                      };
                    })
                  : null,
            };
          })
        : null;
    },

    // 刷新按钮权限
    updatePerms() {
      userService.getMenu().then(res => {
        // 过滤按钮权限
        const btnList = res.data.menuList.filter(item => item.type === 2);
        localStorage.setItem(process.env.VUE_APP_USER_PERMS, JSON.stringify(btnList));
      });
    },
  },
};
</script>

<style lang="less" scoped>
@import './index.less';
</style>
